package tema;

import java.util.Comparator;

public class Utility {

	/**
	 * Maximul unui sir
	 * 
	 * @param coll
	 * @param comp
	 * @return
	 */

	public static <T, S extends T> S max(S[] coll, Comparator<? super T> comp) {

		S maxim;
		maxim = coll[0];
		for (S temp1 : coll) {
			if (comp.compare(temp1, maxim) > 0) {
				maxim = temp1;
			}
		}

		return maxim;
	}

	/**
	 * binary search
	 * 
	 * @param list
	 * @param key
	 * @param c
	 * @return
	 */
	public static <T, S extends T> int binarySearch(S[] list, T key,
			Comparator<? super T> c) {

		int n = (list.length) / 2;

		while (n > 0 && n<list.length) {
			System.out.println("Compar cu "+n);
			if (c.compare(key, list[n]) > 0) {
				n = n + (n / 2);
			} else if (c.compare(key, list[n]) < 0) {
				n = n - (n / 2);
			} else if (c.compare(key, list[n]) == 0) {
				return n;
			}
		}

		return -1;
	}

	/**
	 * sortarea listei
	 * 
	 * @param list
	 */
	public static <T extends Comparable<? super T>> void sort(T[] list) {

		for (int i = 0; i < list.length; i++) {
			for (int j = i + 1; j < list.length; j++) {
				if (list[i].compareTo(list[j]) > 0) {
					T temp = list[i];
					list[i] = list[j];
					list[j] = temp;
				}
			}
		}
	}

	/**
	 * inlocuirea ultimelor 2 elemente cu valoarea maximului si pozitia acestuia
	 * 
	 * @param c
	 * @param elements
	 */
	@SafeVarargs
	public static <T, S extends T> void modifyRear(S[] c, T... elements) {

		  
		for (int i = 0; i < elements.length; i++) {
			
			c[c.length-elements.length+i]= (S)elements[i];
		}

	}

}
